package com.lyn.auxiliarytool.contract.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件管理器
 *
 * @author longyn 2022/11/29
 * @version 1.0.0
 */
public class FileUtil {

    /**
     * 创建文件夹
     *
     * @param path 路径
     * @return 文件夹路径
     */
    public static String createFolder(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    /**
     * 创建文件
     *
     * @param path 路径
     * @return 文件夹路径
     */
    public static String createFile(String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        }
        return file.getAbsolutePath();
    }

    /**
     * 写入文件流
     *
     * @param in  输入流
     * @param out 输出流
     * @throws IOException io异常
     */
    public static void inputStreamToOutPutStream(InputStream in, OutputStream out) throws IOException {
        int len;
        byte[] buff = new byte[1024];
        while ((len = in.read(buff)) > 0) {
            out.write(buff, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }


    /**
     * 拷贝文件到指定目录下
     * @param file 文件
     * @param folderPath 文件夹路径
     * @return 文件夹下的文件路径
     * @throws IOException io异常
     */
    public static String copyFileToFolder(File file, String folderPath) throws IOException {
        FileInputStream in = new FileInputStream(file);
        File newFile = new File(folderPath, file.getName());
        if (!newFile.exists()) {
            newFile.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(newFile);
        inputStreamToOutPutStream(in, out);
        return newFile.getAbsolutePath();
    }

    /**
     * 根据输入流在指定目录下创建文件
     * @param in 输入流
     * @param fileName 文件名称
     * @param folderPath 文件夹路径
     * @return 文件路径
     * @throws IOException io异常
     */
    public static String copyFileToFolder(InputStream in,String fileName, String folderPath) throws IOException {
        File newFile = new File(folderPath, fileName);
        if (!newFile.exists()) {
            newFile.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(newFile);
        inputStreamToOutPutStream(in, out);
        return newFile.getAbsolutePath();
    }

}
